<template>
  <select
    class="form-control select2"
    data-toggle="select2"
    v-model.number="cityId0"
    :id="id"
    style="min-width: 900px"
  >
    <option value="0">请选择城市</option>
    <template v-for="info in cityList">
      <option :value="info.id">
        {{ info.cityEnglishName.toUpperCase() }} - {{ info.cityName }}
      </option>
    </template>
  </select>
</template>


<script>
import $ from "jquery";
import { getAllCities } from "@/api/basic-data.js";

export default {
  props: {
    id: "",
    cityId: {
      type: Number,
      value: 0,
    },
    cityList: {
      type: Array,
    },
  },
  data() {
    return {
      filterTerm: "",
      cityId0: 0,
    };
  },
  mounted: function () {
    const vm = this;
    $(this.$el)
      .select2({
        data: this.cityList,
        placeholder: "请选择城市",
        matcher: this.matchCitySelect,
      })
      .val(this.cityId0)
      .trigger("change")
      .on("change", function () {
        vm.$emit("update:cityId", parseInt(this.value));
      });
  },
  watch: {
    cityId0: function (value) {
      $(this.$el).val(value).trigger("change");
    },
  },
  destroyed: function () {
    $(this.$el).off().select2("destroy");
  },
  methods: {
    matchCitySelect: function (params, data) {
      // If there are no search terms, return all of the data
      if ($.trim(params.term) === "") {
        return data;
      }

      // Do not display the item if there is no 'text' property
      if (typeof data.text === "undefined") {
        return null;
      }

      // `params.term` should be the term that is used for searching
      // `data.text` is the text that is displayed for the data object
      if (
        data.text.indexOf(params.term.toUpperCase()) > -1 ||
        data.title.indexOf(params.term.toUpperCase()) > -1
      ) {
        return data;
        // var modifiedData = $.extend({}, data, true);
        // modifiedData.text += ' (matched)';

        // You can return modified objects from here
        // This includes matching the `children` how you want in nested data sets
        // return modifiedData;
      }

      // Return `null` if the term should not be displayed
      return null;
    },
  },
};
</script>
